﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HP.Datastore.Common;
using Widgetsphere.Autos.API;
using Widgetsphere.Autos.API.FacetedNavigation;

namespace Widgetsphere.Autos.Websitev2.UserControls
{
    public partial class GeoSearchControl : System.Web.UI.UserControl
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            this.Visible = ConfigHelper.AllowZipSearch;

            cboDistance.Items.Add(new ListItem("10 miles", "10"));
            cboDistance.Items.Add(new ListItem("20 miles", "20"));
            cboDistance.Items.Add(new ListItem("30 miles", "30"));
            cboDistance.Items.Add(new ListItem("40 miles", "40"));
            cboDistance.Items.Add(new ListItem("50 miles", "50"));
            cboDistance.Items.Add(new ListItem("100 miles", "100"));
            cboDistance.SelectedIndex = 1;

            cmdGo.Click += cmdGo_Click;

            var url = new ListingQuery(this.Request.Url.PathAndQuery);
            txtZip.Text = url.NonParsedFieldList["location"];
            if (string.IsNullOrEmpty(txtZip.Text))
                txtZip.Text = url.NonParsedFieldList["zip"];

            var ff = url.FieldFilters.FirstOrDefault(x => x is HP.Datastore.Common.GeoCodeFieldFilter) as HP.Datastore.Common.GeoCodeFieldFilter;
            if (ff != null)
                cboDistance.SelectedValue = ff.Radius.ToString();


        }

        private void cmdGo_Click(object sender, EventArgs e)
        {
            var info = GeoLocationHelper.GetZipInfo(txtZip.Text);
            if (info != null)
            {
                var url = new ListingQuery(this.Request.Url.PathAndQuery);
                url.FieldFilters.RemoveAll(x => x is FieldFilterLocation);
                url.NonParsedFieldList.RemoveAll(x => x.Key == "zip");
                url.NonParsedFieldList.RemoveAll(x => x.Key == "rd");

                var radius = Convert.ToInt32(cboDistance.SelectedValue);
                url.FieldFilters.Add(new FieldFilterLocation() { Latitude = info.Latitude, Longitude = info.Longitude, Radius = radius });
                url.NonParsedFieldList.Add(new NamedItem() { Key = "zip", Value = txtZip.Text });
                url.NonParsedFieldList.Add(new NamedItem() { Key = "rd", Value = cboDistance.SelectedValue });
                url.PageOffset = 1;
                this.Response.Redirect(url.ToString());
            }
            else
            {
                //Not found
            }

        }

    }
}